﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace OpenFlashChartLib.Json
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
    public class JsonTextAttribute : Attribute
    {
        string PropertyName { get; set; }

        public JsonTextAttribute(string textPropertyName)
        {
            PropertyName = textPropertyName;
        }

        /// <summary>
        /// Gets the name specified for use in Json serialization.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetTextFieldName(object value)
        {
            if (value == null)
            {
                return null;
            }

            Type type = value.GetType();
            if (type == null)
            {
                throw new ArgumentException();
            }

            if (!IsDefined(type, typeof(JsonTextAttribute)))
            {
                return null;
            }
            var attribute = (JsonTextAttribute)GetCustomAttribute(type, typeof(JsonTextAttribute));

            return attribute.PropertyName;
        }

        /// <summary>
        /// Returns object field value
        /// </summary>
        /// <param name="value"></param>
        /// <param name="fieldName"></param>
        /// <returns></returns>
        public static object GetFieldValue(object value, string fieldName)
        {
            if (value == null)
                return null;
            Type type = value.GetType();
            PropertyInfo prop = type.GetProperty(fieldName);
            return prop.GetValue(value, null);
        }

    }
}
